package com.ctshk.common.utils;

import com.ctshk.common.enums.SystemError;
import com.ctshk.common.exception.BusinessException;
import org.apache.commons.collections.CollectionUtils;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.groups.Default;
import java.util.Set;

/**
 * <p>
 *
 * </p>
 *
 * @author 胡广
 * @since 2021/5/10
 */
public class ValidatorUtil {
    public static <T> void validate(T targetObject) {
        Set<ConstraintViolation<T>> validateSet = Validation.buildDefaultValidatorFactory()
                .getValidator()
                .validate(targetObject, Default.class);
        if (CollectionUtils.isNotEmpty(validateSet)) {
            String messages = validateSet.stream()
                    .map(ConstraintViolation::getMessage)
                    .reduce((m1, m2) -> m1 + ";" + m2)
                    .orElse("参数输入有误！");
            throw new BusinessException(SystemError.SYS_430, messages);
        }
    }
}
